package com.cipe.cmrs.controllers;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.cipe.cmrs.model.User;
import com.cipe.cmrs.service.UserService;
import com.cipe.cmrs.util.PasswordEncryptionUtil;

@Controller
@RequestMapping("/login.do")
public class LoginController extends BaseController {

	private static final long serialVersionUID = 2953245877386975346L;
	private static final String COMMAND_NAME = "user";
	private String formView = "loginerr";
	private String successView = "success";

	@Autowired
	private UserService userService;

	@ModelAttribute(COMMAND_NAME)
	public User getCommand() {
		//System.out.println("getCommand:________");
		return new User();
	}
    
	
	
	@RequestMapping( method = RequestMethod.GET)
	public String showForm(HttpSession session, Model model) {
		//System.out.println("showForm:________");
		if (session.getAttribute(User.LOGGED_IN_USER_KEY) != null) {
			return "redirect:/secure/showDashboard.do";
		}
		model.addAttribute("user", new User());
		return "login";
	}
       
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onSubmit(@ModelAttribute("user") User user, BindingResult result, SessionStatus status, HttpServletRequest request) throws Exception {
		ModelAndView mav = null;
		System.out.println("onSubmit:________");
		//User dbUser = userService.authenticUser(user);
		User dbUser = userService.getUserByLoginName(user.getLoginName().toLowerCase());
		String encryptPassword = PasswordEncryptionUtil.getEncryptedPassword(user.getPassword());
		 if (dbUser == null) {
				mav = new ModelAndView(formView);
				mav.addAllObjects(result.getModel());
				mav.addObject("errorMessage", getText("error.invaliduser"));
			//System.out.println("erro.invaliduser "+ getText("error.invaliduser") );
		} else if(!encryptPassword.equals(dbUser.getPassword())){
			mav = new ModelAndView(formView);
			mav.addAllObjects(result.getModel());
			mav.addObject("errorMessage", getText("error.invalidPassword"));

		} else {
			mav = new ModelAndView(successView);
			request.getSession().setAttribute(User.LOGGED_IN_USER_KEY, dbUser.getId());	
		}
		return mav;
	}
}
